package com.cardbaobao.cardbabyclient.model.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.cardbaobao.cardbabyclient.model.database.CbbDataBase;
import com.cardbaobao.cardbabyclient.model.database.SQL;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jiangzx on 2017/7/12 11:29.
 */

public class LauncherAdClickedDao {
    /**首页广告点击表名*/
    private static final String TABLE_NAME= SQL.TABLE_LAUNCHER_AD_CLICKED;
    private static final String KEY_URL="url";

    private SQLiteDatabase mDataBase;

    public LauncherAdClickedDao(){
        init();
    }

    private synchronized SQLiteDatabase init(){
        CbbDataBase dataBaseHelper=
                new CbbDataBase(ApplicationHelper.getApplicationContext(),
                        SQL.DB_NAME,null,SQL.DB_VERSION);
        if(mDataBase==null||!mDataBase.isOpen()){
            mDataBase=dataBaseHelper.getWritableDatabase();
        }
        return mDataBase;
    }

    private void closeDateBase(){
        if(null!=mDataBase){
            mDataBase.close();
            mDataBase=null;
        }
    }

    /**
     * 获取所有已点击的广告链接
     * @return 已点击的广告url列表
     */
    public List<String> getAllClickedAdUrl(){
        init();
        List<String> list = new ArrayList<>();
        Cursor cursor=mDataBase.query(TABLE_NAME,new String[]{KEY_URL},null,null,null,null,null);
        if(cursor!=null){
            if(cursor.moveToFirst()){
                for(int i=0,size=cursor.getCount();i<size;i++){
                    list.add(cursor.getString(cursor.getColumnIndex(KEY_URL)));
                    cursor.moveToNext();
                }
            }
            cursor.close();
        }
        closeDateBase();
        return list;
    }

    public void inSertClickedAdUrl(String url){
        if(!TextUtils.isEmpty(url)){
            init();
            ContentValues values=new ContentValues(1);
            values.put(KEY_URL,url);
            mDataBase.insert(TABLE_NAME,null,values);
            closeDateBase();
        }
    }
}
